package com.dx.wx.util;

import com.ejlchina.data.Array;
import com.ejlchina.data.Mapper;
import com.ejlchina.okhttps.HttpResult;
import com.ejlchina.okhttps.OkHttps;
import com.ejlchina.okhttps.SHttpTask;
import com.ejlchina.okhttps.internal.ResultBody;
import com.yf.response.RRException;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class DxUtil {

    @Value("${DX.app-id}")
    private String appId;

    @Value("${DX.app-secret}")
    private String appSecret;

    @Value("${DX.permanent-code}")
    private String permanentCode;

    private static String currentOpenUserId;

    public static String CorpAccessToken;

    public static String CorpId;

    public static int ExpiresIn = 0;

//    public static int expiresIn;


    /**
     * http://open.fxiaoke.com/wiki.html#artiId=1018
     * 修改数据
     *
     * @param data {object_data:{dataObjectApiName,_id}}
     */
    public static void update(Map data) {
        String url = "https://open.fxiaoke.com/cgi/crm/custom/v2/data/update";
        Mapper mapper = OkHttps(url).addBodyPara("data", data).post().getBody().toMapper();
        validate(mapper, "更新错误!");
    }

    /**
     * 修改客户负责人
     * http://open.fxiaoke.com/wiki.html#artiId=264
     *
     * @param data
     */
    public static void changeOwner(Map data) {
        String url = "https://open.fxiaoke.com/cgi/crm/v2/data/changeOwner";
        Mapper mapper = OkHttps(url).addBodyPara("data", data).post().getBody().toMapper();
        validate(mapper, "修改负责人错误!");
    }


    /**
     * http://open.fxiaoke.com/wiki.html#artiId=1017
     * 新增数据
     *
     * @param data
     */
    public static Mapper save(Map data) {
        String url = "https://open.fxiaoke.com/cgi/crm/custom/v2/data/create";
        Mapper mapper = OkHttps(url).addBodyPara("data", data).post().getBody().toMapper();
        validate(mapper, "新增错误!");
        return mapper;
    }


    /**
     * https://open.fxiaoke.com/wiki.html#artiId=1370
     * 根据条件查找一个
     *
     * @param data {search_query_info,field_projection}
     * @return
     */
    public static Mapper findOne(Map data) {
        String url = "https://open.fxiaoke.com/cgi/crm/custom/v2/data/findOne";
        Mapper mapper = OkHttps(url).addBodyPara("data", data).post().getBody().toMapper();
        validate(mapper, "单个查找失败");
        return mapper.getMapper("data").getMapper("objectData");
    }

    //添加APPID查询
    public static Map addAppIdFilter(String appId) {
        Map filter = new HashMap<>();
        appId = getAppId(appId);
        filter.put("field_name", "app_id__c");
        filter.put("field_values", appId);
        filter.put("operator", "EQ");
        return filter;
    }

    public static String getAppId(String appId) {
        if (appId == null || appId.equals("")) { //默认上动销
            return "wx46491efef1420c1e";
        }
        return appId;
    }


    /**
     * https://open.fxiaoke.com/wiki.html#artiId=1372
     * 根据条件简单查询
     *
     * @param data {search_query_info,field_projection,need_return_count_num}
     * @return
     */
    public static Array findSimple(Map data) {
        String url = "https://open.fxiaoke.com/cgi/crm/custom/v2/data/findSimple";
        Mapper mapper = OkHttps(url).addBodyPara("data", data).post().getBody().toMapper();
        validate(mapper, "简单列表查询失败");
        return mapper.getMapper("data").getArray("dataList");
    }

    /**
     * 下载素材
     * http://open.fxiaoke.com/wiki.html#artiId=66
     *
     * @param response
     * @param media
     */
    public static void download(HttpServletResponse response, String mediaId) {
        String url = "https://open.fxiaoke.com/media/download";
        SHttpTask sHttpTask = OkHttps.sync(url).bodyType(OkHttps.JSON).addBodyPara("currentOpenUserId", getAdminOpenUserId()).addBodyPara("corpAccessToken", CorpAccessToken).addBodyPara("corpId", CorpId).addBodyPara("mediaId", mediaId);
        if (mediaId.contains("N_")) {
            sHttpTask.addBodyPara("mediaTypeDesc", "DOCUMENT");
            sHttpTask.addBodyPara("igonreMediaIdConvert", true);
        }
        InputStream stream = sHttpTask.post().getBody().toByteStream();
        try {
            ImageIO.write(ImageIO.read(stream), "jpeg", response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * http://open.fxiaoke.com/wiki.html#artiId=65
     *
     * @param file
     */
    public static Mapper upload(MultipartFile file) {
        String url = "https://open.fxiaoke.com/media/upload";
        try {
            System.out.println(new Date() + " 请求图片中");
            Mapper mapper = OkHttps(url).addBodyPara("type", "image").addFilePara("media", "jpg", file.getBytes()).post().getBody().toMapper();
            System.out.println(new Date() + " CRM图片结果:" + mapper.toString());
            DxUtil.validate(mapper, "图片上传失败" + mapper.getString("errorMessage"));
            if (mapper.getString("mediaId") == null || mapper.getString("mediaId").equals("")) {
                System.out.println("上传失败:" + mapper);
                throw new RRException("上传失败!" + mapper.getString("errorMessage"));
            }
            return mapper;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RRException("上传失败");
        }
    }

    private static SHttpTask OkHttps(String url) {
        return OkHttps.sync(url).bodyType(OkHttps.JSON).addBodyPara("corpAccessToken", CorpAccessToken).addBodyPara("corpId", CorpId).addBodyPara("currentOpenUserId", getAdminOpenUserId());
    }


    /**
     * 定时获取TOKEN
     * 500秒获取一次
     */
    @Scheduled(
            fixedDelay = 500 * 1000
    )
    public void autoToken() {
        CorpAccessToken = getCorpAccessToken(this.appId, this.appSecret, this.permanentCode);
    }

    /**
     * http://open.fxiaoke.com/wiki.html#artiId=17
     * 获取CorpAccessToken
     *
     * @param appId
     * @param appSecret
     * @param permanentCode
     * @return
     */
    public static String getCorpAccessToken(String appId, String appSecret, String permanentCode) {
        String url = "https://open.fxiaoke.com/cgi/corpAccessToken/get/V2";
        Mapper mapper = OkHttps.sync(url).bodyType(OkHttps.JSON).addBodyPara("appId", appId).addBodyPara("appSecret", appSecret).addBodyPara("permanentCode", permanentCode)
                .post()                          // GET请求
                .getBody().toMapper();
        validate(mapper, "获取CorpAccessToken");
        CorpId = mapper.getString("corpId");
        ExpiresIn = mapper.getInt("expiresIn");//过期时间 小于600秒就可以获取新的
        return mapper.getString("corpAccessToken");
    }


    /**
     * 获取管理员openUserId
     *
     * @return
     */
    public static String getAdminOpenUserId() {
        if (currentOpenUserId == null) {
            String mobile = "13929987869";
            currentOpenUserId = DxUtil.getUserInfo(mobile).getString("openUserId");
        }
        return currentOpenUserId;
    }


    /**
     * 获取管理员openUserId
     *
     * @return
     */
    public static String getOpenUserId(String mobile) {
        Mapper mapper = DxUtil.getUserInfo(mobile);
        if (mapper == null) {
            return null;
        }
        return mapper.getString("openUserId");
    }


    /**
     * https://open.fxiaoke.com/wiki.html#artiId=1122
     * 根据手机号查询员工信息
     */
    public static Mapper getUserInfo(String mobile) {
        String url = "https://open.fxiaoke.com/cgi/user/getByMobile";
        Mapper mapper = OkHttps.sync(url).bodyType(OkHttps.JSON).addBodyPara("corpAccessToken", CorpAccessToken).addBodyPara("corpId", CorpId).addBodyPara("mobile", mobile).post().getBody().toMapper();
        validate(mapper, "根据手机号查询员工信息");
        return mapper.getArray("empList").getMapper(0);
    }


    public static void validate(Mapper mapper, String msg) {
        if (mapper.getInt("errorCode") != 0) {
            System.out.println("CRM错误:" + mapper.getString("errorMessage"));
            throw new RRException(msg + "错误:" + mapper.getString("errorMessage"));
        }
    }


    public static Map createSearchData(Map... filters) {
        List filtersA = Arrays.stream(filters).filter(item -> item != null).collect(Collectors.toList());
        Map data = new HashMap();
        Map searchInfo = new HashMap();
        searchInfo.put("limit", 1000);
        searchInfo.put("filters", filtersA);
        data.put("search_query_info", searchInfo);
        return data;
    }

    public static Map createSearchData(List<Map> filters, List<Map> orders) {
        Map data = new HashMap();
        Map searchInfo = new HashMap();
        searchInfo.put("limit", 1000);
        searchInfo.put("filters", filters);
        searchInfo.put("orders", orders);
        data.put("search_query_info", searchInfo);
        return data;
    }

    public static Map createMergeData(Map objectData) {
        Map data = new HashMap();
        data.put("object_data", objectData);
        return data;
    }

    public static Map createChangeOwnerData(String ownerId, String dataId) {
        Map data = new HashMap();
        Map Data = new HashMap();
        Data.put("ownerId", Arrays.asList(ownerId.trim()));
        Data.put("objectDataId", dataId.trim());
        data.put("Data", Arrays.asList(Data));
        return data;
    }


}
